﻿@page "/UpdateCompany"
@using Microsoft.Extensions.Options
@using Newtonsoft.Json
@using WorkFlow.Data
@using WorkFlow.Data.Model
@using System.Net.Http

@inject IOptions<List<CompanyApiAddressEntity>> settings
@inject List<CompanyApiAddressEntity> companyAddressModels
@inject List<PlatformInfo> platformInfos
@inject List<CompanyInfo> companyInfos
@inject DataManager dataManager
@inject IJSRuntime JSRunTime
<h3>UpdateCompany</h3>

<div>
    &nbsp;&nbsp;API&nbsp;<select id="api" @bind="@_Api">
        @if (companyAddressModels != null)
        {
            for (var i = 0; i < companyAddressModels.Count; i++)
            {
                CompanyApiAddressEntity entity = companyAddressModels[i];
                <option value=@entity.CompanyApiAddress>@entity.CompanyApiAddress</option>
            }
        }
    </select>
    &nbsp;&nbsp;Platform&nbsp;<select id="platformInfo" @bind="@_PlatformID">
        @if (platformInfos != null)
        {
            for (var i = 0; i < platformInfos.Count; i++)
            {
                PlatformInfo entity = platformInfos[i];
                <option value=@entity.ID>@entity.Name</option>
            }
        }
    </select>
    &nbsp;&nbsp;<button @onclick="@(()=>Refresh())" class="btn btn-primary btn-xs">Refresh</button>
    &nbsp;&nbsp;<button @onclick="@(()=>Save())" class="btn btn-primary btn-xs">Save</button>
</div>
@_UpdateContent
<table class="table">
    <thead>
        <tr>
            <th>Sno</th>
            <th>ID</th>
            <th>CompanyName</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        @if (companyInfos != null)
            @for (var i = 0; i < companyInfos.Count; i++)
            {
                CompanyInfo companyInfo = companyInfos[i];
                <tr>
                    <td>@(i+1)</td>
                    <td>@companyInfo.ID</td>
                    <td>@companyInfo.Name</td>
                    <td>@companyInfo.Opration</td>
                </tr>
            }
    </tbody>
</table>

@code {
    private IJSObjectReference module;
    string _UpdateContent;
    string _Api;
    int _PlatformID = -1;
    protected override async void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            module = await JSRunTime.InvokeAsync<IJSObjectReference>("import", "/vendor/MyJS.js");
            companyAddressModels = settings.Value;
            platformInfos = dataManager.GetPlatformInfos();
            if (companyAddressModels.Count > 0)
                _Api = companyAddressModels[0].CompanyApiAddress;
            if (platformInfos.Count > 0)
                _PlatformID = platformInfos[0].ID;
            UpdateUI();
        }
    }
    async void Refresh()
    {
        if (_PlatformID == -1 && string.IsNullOrEmpty(_Api))
        {
            await module.InvokeVoidAsync("alertMsg", "Please select API and Platform");
            return;
        }
        List<CompanyInfo> oldCompanyInfos = dataManager.GetCompanyInfos(_PlatformID);
        List<CompanyInfo> newCompanyInfos = GetHttp<List<CompanyInfo>>(_Api, _PlatformID);
        if (newCompanyInfos != null)
        {
            companyInfos = new List<CompanyInfo>();
            // Add Delete or Update Company
            for (var i = 0; i < oldCompanyInfos.Count; i++)
            {
                CompanyInfo oldCompanyInfo = oldCompanyInfos[i];
                CompanyInfo newCompanyInfo = newCompanyInfos.Find(x => x.ID == oldCompanyInfo.ID);
                if (newCompanyInfo == null)
                {
                    oldCompanyInfo.Opration = OprationType.Delete;
                    companyInfos.Add(oldCompanyInfo);
                }
                else if (newCompanyInfo.Name != oldCompanyInfo.Name)
                {
                    newCompanyInfo.Opration = OprationType.Update;
                    companyInfos.Add(newCompanyInfo);
                }
            }
            // Add New Company
            for (var i = 0; i < newCompanyInfos.Count; i++)
            {
                CompanyInfo newCompanyInfo = newCompanyInfos[i];
                CompanyInfo oldCompanyInfo = oldCompanyInfos.Find(x => x.ID == newCompanyInfo.ID);
                if (oldCompanyInfo == null)
                {
                    newCompanyInfo.Opration = OprationType.Add;
                    companyInfos.Add(newCompanyInfo);
                }
            }
            _UpdateContent = $"All Total Num:【{companyInfos.Count}】 Add Num:【{companyInfos.FindAll(a => a.Opration == OprationType.Add).Count}】"
               + $" Delete Num:【{companyInfos.FindAll(a => a.Opration == OprationType.Delete).Count}】 Update Num:【{companyInfos.FindAll(a => a.Opration == OprationType.Update).Count}】";
        }
        else
        {
            await module.InvokeVoidAsync("alertMsg", $"Get Company Error Api:{_Api} Platform:{_PlatformID}");
        }
        UpdateUI();
    }

    async void Save()
    {
        if (_PlatformID == -1 && string.IsNullOrEmpty(_Api))
        {
            await module.InvokeVoidAsync("alertMsg", "Please select API and Platform");
            return;
        }
        string message = dataManager.SaveCompanyInfos(companyInfos, _PlatformID);
        if (!string.IsNullOrEmpty(message))
        {
            await module.InvokeVoidAsync("alertMsg", "Save Fail:" + message);
            return;
        }
        await module.InvokeVoidAsync("alertMsg", "Save Success!");
        companyInfos = new List<CompanyInfo>();
        UpdateUI();
    }

    T GetHttp<T>(string api, int platformID)
    {
        try

        {
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage message = httpClient.GetAsync(api + $"?PlatformID={platformID}").Result;
            bool result = message.StatusCode == System.Net.HttpStatusCode.OK;
            if (result)
            {
                return message.Content.ReadAsAsync<T>().Result;
            }
        }
        catch (Exception ex)
        {
            LogHelper.WriteLog("Err GetHttp:", ex);
        }
        return default(T);
    }

    public string SerializeJson<T>(T obj, int indentation = 0, char indentchar = ' ')
    {
        StringWriter writer = new StringWriter();
        JsonTextWriter jsoonWriter = new JsonTextWriter(writer)
            {
                Formatting = Formatting.Indented,
                Indentation = indentation,
                IndentChar = indentchar
            };
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(jsoonWriter, obj);
        return writer.ToString();
    }
    public static T DeserializeJson<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

    private async void UpdateUI()
    {
        await InvokeAsync(() => StateHasChanged());
    }
}
